import { defineConfig, loadEnv } from "vite";
import { resolve } from "path";
// import { createVuePlugin } from "vite-plugin-vue2"; // 不支持vue2.7以上
import vue from "@vitejs/plugin-vue2"; // 支持vue 2.7以上版本 原因待排查
import vueJsx from "@vitejs/plugin-vue2-jsx";
import { createHtmlPlugin } from "vite-plugin-html";
// import vitePluginImp from "vite-plugin-imp";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { visualizer } from "rollup-plugin-visualizer";

import * as packageJson from "./package.json";

function pathResolve(dir) {
  return resolve(process.cwd(), ".", dir);
}

// TODO: build后可能要处理icon偶发乱码的情况 css-unicode-loader
export default ({ mode }) => {
  const root = process.cwd();

  const env = loadEnv(mode, root);

  const publicPath = env.VITE_BASE_PATH;

  return defineConfig({
    base: publicPath + "/", // 设置打包路径
    outDir: "dist", // 设置打包路径
    envPrefix: ["VITE_", "VUE_APP_"],
    define: {
      __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
    },
    plugins: [
      vue(),
      vueJsx(),
      // createVuePlugin(),
      // vitePluginImp({
      //   libList: [
      //     {
      //       libName: "element-ui",
      //       libDirectory: "lib",
      //       style(name) {
      //         return `element-ui/packages/theme-chalk/src/${name}.scss`;
      //       },
      //     },
      //   ],
      // }),
      createHtmlPlugin({
        inject: {
          data: {
            version: packageJson.version,
          },
        },
        minify: true,
      }),
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [resolve(process.cwd(), "src/assets/icons")],
        // Specify symbolId format
        symbolId: "icon-[dir]-[name]",
      }),
      visualizer({
        open: false, //注意这里要设置为true，否则无效
        gzipSize: true,
        brotliSize: true,
      }),
    ],
    esbuild: {
      jsxFactory: "h",
      jsxFragment: "Fragment",
    },
    resolve: {
      // 路径别名
      alias: {
        "@": pathResolve("src"),
      },
      // 省略文件后缀
      extensions: ["", ".js", ".json", ".vue", ".scss", ".css"],
    },
    server: {
      host: "0.0.0.0",
      port: 9000,
      open: true,
      proxy: {
        // "/api": {
        //   target: env.VITE_APP_BASE_URL,
        //   pathRewrite: { "^/api": "" },
        //   ws: true,
        //   changeOrigin: true,
        // },
        "/costume_change": {
          target: env.VITE_APP_BASE_URL,
          pathRewrite: { "^/costume_change": "" },
          ws: true,
          changeOrigin: true,
        },
      },
    },
    build: {
      sourcemap: false,
      minify: "terser",
      // minify: false,
      chunkSizeWarningLimit: 1500,
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id.toString().split("node_modules/")[1].split("/")[0].toString();
            }
          },
          chunkFileNames: (chunkInfo) => {
            const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split("/") : [];
            const fileName = facadeModuleId[facadeModuleId.length - 2] || "[name]";
            return `js/${fileName}/[name].[hash].js`;
          },
        },
      },
    },
  });
};
